import fs from 'fs-extra';
import path from 'path';
import formidable from 'formidable';
import Config from '../conf';
const decompress = require('decompress');
const decompressUnzip = require('decompress-unzip');
const rim = require('rimraf');
 

export default async function uploadFiles(cx,next){
	let {support, uploadedDir} = Config.upload;
	if (!support) return false;
	
  let {user, md='0', vs, v} = cx.request.query;

	let body = {
		success: true,
		result: 'ok'
	}

    const form = new formidable.IncomingForm();
    form.uploadDir = uploadedDir;
    form.keepExtensions = true;
  	
    async function unzip(zip, dir) {
      var ziped=true;
      try {
        await decompress(zip, dir, {
              plugins: [
                  decompressUnzip()
              ]
          });
      } catch(e) {
        console.log('unzip failed!');
        ziped = false;
      }
      return ziped;
    }
    async function bookCtrl(files) {
      var tempid=Math.random().toString(23).slice(0, 15)
      var _dir=path.resolve(process.cwd(), uploadedDir);
      var userDir='/' + tempid;//'/'+user;
      var isUserDir=fs.existsSync(_dir+userDir);
      if (!isUserDir) {
        fs.mkdirSync(_dir + userDir);
      }
      var bookDir='/' + files.name.replace(/\.\w+$/,'');
      
      var dir = _dir + userDir + bookDir;
      var isExists = fs.existsSync(dir);
      if (isExists) rim.sync(dir);

      fs.mkdirSync(dir);
      var ziped=await unzip(files.path,dir);
      process.nextTick(() => {
        fs.unlinkSync(files.path);
      });
      if (!ziped) {
        try {
          fs.removeSync(dir);
        }catch(e) {
          console.log(e);
        }
        return Promise.resolve({
          success: false,
          result: '附件解压失败！'
        });
      }
      
      return new Promise((a,b) => {
        var book = {};
        try {
          book = JSON.parse(fs.readFileSync(dir+'/book.json').toString());
        } catch(e) {
          console.log(e);
        }
        if (book.logo && !/^(https?:)?\/\//.test(book.logo)) {
          book.logo = path.join(userDir,book.logo);
        }
        book.isMdpage = fs.existsSync(dir+'/SUMMARY.md')?1:0;
        book.bookDir = bookDir;
        book.tempid = tempid;
        book.version = book.version||'1.0.0';
        if (md != book.isMdpage && md != -1) {
          try {
            fs.remove(_dir + userDir);
          } catch(e) {}
          a({
            success:false,
            result: 'html版和markdown版电子书暂不支持混淆'
          });
        } else if (book.version && v && vs && book.version != v && ~vs.split(',').indexOf(book.version)) {
          try {
            fs.remove(_dir + userDir);
          } catch(e) {}
          a({
            success: false,
            result: '请修改版本号或选择其他版本'
          });
        } else {
          a({
            book
          });
        }
        
      });
    }
    async function upload() {
      
      let _user=await cx.locServe.users.find({name: user});
      
      return new Promise((a,b) => {
        try {
          form.parse(cx.req, (err, fields, files) => {
            var files = files.fileupload;
            if (!_user.length) {
              try{fs.unlinkSync(files.path);} catch(e) {}
              a({
                success: false,
                result: '用户不存在！'
              });
            } else {
              a(files);
            }
            
          });
        } catch(e) {
          console.log(e);
          b(e);
          body={
            success: false,
            result: e.message
          }
        }  
      });
    }
    let files = await upload();
    if (files.success !== undefined) {
      cx.response.body = files;
      return;
    }
    let book = await bookCtrl(files);
    if (book.success === false) {
      body = book;
    } else {
      body.result = book;
    }
	  cx.response.body = body;
}